﻿using System;
using System.Collections;
using SuperiorCommon;

namespace Redis
{
    /// <summary>
    /// redis数据与数据库数据
    /// </summary>
    public class DataIntegration
    {
        /// <summary>
        /// //封装先从缓存取数据，没有，从数据库取数据，再存到缓存的过程
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="func"></param>
        /// <returns></returns>
        public static T GetData<T>(string key, Func<T> func, int hours = 24)
        {
            try
            {
                T result = RedisManager.Get<T>(key);
                if (result == null)
                {
                    result = func();
                    if (result != null)
                    {
                        if (result is ICollection)
                        {
                            var temp = result as ICollection;
                            if (temp.Count > 0)
                            {
                                RedisManager.Set<T>(key, result, DateTime.Now.AddHours(hours));
                            }
                        }
                        else
                        {
                            RedisManager.Set<T>(key, result, DateTime.Now.AddHours(hours));
                        }

                    }
                }
                return result;
            }
            catch(Exception ex)
            {
                LogManger.Instance.WriteLog("读取redis中间件异常，可能redis挂了、" + ex.ToString());
                //直接返回数据库数据，防止业务程序走不通
                return func();
            }


        }
    }
}
